package co.yixiang.modules.shop.utils;

import org.apache.commons.lang3.StringUtils;

import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;


/**
 * @author
 */
public class SequenceIdGenerateUtils {

  // private static final long BEGIN_DATE =DateUtils.parseString2Date("2016-01-01", "yyyy-MM-dd").getTime();
  private static String ip = "";

  //private static int businessType =1 ;
   
   /*static{	   
    try {
		InetAddress addr = InetAddress.getLocalHost();
		ip=addr.getHostAddress();
	} catch (UnknownHostException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}	   
   }*/

  //private static final int localMachineAppend = Integer.parseInt(ip.split("\\.")[3]);

  private static AtomicInteger atomicInteger = new AtomicInteger(0);

  public static long generate() {
    StringBuilder binaryStr = new StringBuilder("0");
    binaryStr.append(wrapTimeBinaryStr());
    //binaryStr.append(wrapBusinessBinaryStr(businessType));

    //binaryStr.append(wrapRoomBinaryStr(1));

    //binaryStr.append(wrapMachineBinaryStr(localMachineAppend));

    binaryStr.append(wrapSequencePeyMachine());
    return Long.parseLong(binaryStr.toString(), 2);
  }

  public static String generateId() {
    long gen = generate();
    StringBuilder id = new StringBuilder(DateUtils.formatDate2String(new Date(), "yyyyMMdd") + gen);
    return id.toString();
  }
  public static String generateBatchId() {
    long gen = generate();
    StringBuilder id = new StringBuilder(DateUtils.formatDate2String(new Date(), "yyyyMMddHHmmss") + (int)((Math.random()*9+1)*10000));
    return id.toString();
  }
  /**
   * 39 bit
   */
  private static String wrapTimeBinaryStr() {
    long currentTime = System.currentTimeMillis();
    //long timeElipse = (currentTime - BEGIN_DATE);
    long timeElipse = (currentTime) % (24 * 60 * 60 * 1000);
    return StringUtils.leftPad(Long.toBinaryString(timeElipse), 39, '0');
  }

  /**
   * 10 bit
   */
  private static String wrapMachineBinaryStr(int machineIp) {
    return StringUtils.leftPad(Integer.toBinaryString(machineIp), 10, '0');
  }

  /**
   * 5 bit
   */
  private static String wrapBusinessBinaryStr(int businessType) {
    return StringUtils.leftPad(Integer.toBinaryString(businessType), 5, '0');
  }

  /**
   * 4 bit
   */
  private static String wrapRoomBinaryStr(int room) {
    return StringUtils.leftPad(Integer.toBinaryString(room), 4, '0');
  }

  /**
   * 5 bit
   */
  private static String wrapSequencePeyMachine() {
    if (atomicInteger.get() == Integer.MAX_VALUE) {
      atomicInteger = new AtomicInteger();
    }
    return StringUtils
        .leftPad(Integer.toBinaryString(atomicInteger.incrementAndGet() % 32), 5, '0');
  }

  public static void main(String[] args) {
    System.out.println(SequenceIdGenerateUtils.generateId());
  }
}